import * as Cesium from 'cesium';

class BillboardLayerManager {
  constructor(viewer) {
    if (!viewer) {
      console.error('初始化失败：缺少Cesium Viewer实例');
      return;
    }

    this.viewer = viewer;
    this.currentLayerType = null;
    this.entitiesMap = new Map(); // 存储结构: {type: [{entity, properties, uniqueId}, ...]}
    this.popup = null;
    this.activeEntity = null;
    this.clickHandler = null;
    console.log('BillboardLayerManager 初始化成功');
    this.initPopup();
    this.initEvents();
  }

  /**
   * 初始化弹窗DOM元素
   */
  initPopup() {
    console.log('初始化弹窗');
    if (this.popup) return;

    const popup = document.createElement('div');
    popup.className = 'cesium-popup';
    popup.style.cssText = `
      position: absolute;
      background: white;
      border-radius: 6px;
      box-shadow: 0 3px 14px rgba(0,0,0,0.2);
      padding: 12px;
      z-index: 9999;
      display: none;
      max-width: 320px;
      pointer-events: auto;
      font-family: sans-serif;
    `;
    this.viewer.container.appendChild(popup);
    this.popup = popup;

    // 点击空白处关闭弹窗
    this.viewer.scene.canvas.addEventListener('click', (e) => {
      if (popup.contains(e.target)) {
        return;
      }

      const position = new Cesium.Cartesian2(e.clientX, e.clientY);
      const pickedObject = this.viewer.scene.pick(position);

      const isPickedEntity = Cesium.defined(pickedObject) &&
        Cesium.defined(pickedObject.id) &&
        pickedObject.id.billboard &&
        this.currentLayerType &&
        this.entitiesMap.get(this.currentLayerType)?.some(item =>
          item.uniqueId === pickedObject.id.uniqueId
        );

      if (!isPickedEntity) {
        this.hidePopup();
      }
    });
  }

  /**
   * 初始化事件监听
   */
  initEvents() {
    console.log('初始化事件监听');
    // 相机移动时更新弹窗位置
    this.viewer.scene.postRender.addEventListener(() => {
      this.updatePopupPosition();
    });

    // 绑定实体点击事件
    this.bindEntityClick();
  }

  /**
   * 绑定实体点击事件处理器
   */
  bindEntityClick() {
    console.log('绑定实体点击事件处理器');
    if (this.clickHandler) {
      this.clickHandler.destroy();
    }

    this.clickHandler = new Cesium.ScreenSpaceEventHandler(this.viewer.scene.canvas);
    this.clickHandler.setInputAction((movement) => {
      console.log('点击事件触发');
      const pickedObject = this.viewer.scene.pick(movement.position);
      console.log('拾取对象:', pickedObject);

      if (
        !Cesium.defined(pickedObject) ||
        !pickedObject.id ||
        !pickedObject.id.billboard ||
        !this.currentLayerType
      ) {
        console.log('拾取对象无效或当前无激活图层');
        return;
      }

      const currentEntities = this.entitiesMap.get(this.currentLayerType) || [];
      console.log(`当前图层[${this.currentLayerType}]实体数量:`, currentEntities.length);

      const targetEntity = currentEntities.find(item => {
        return item.uniqueId === pickedObject.id.uniqueId;
      });

      console.log('目标实体:', targetEntity);
      if (targetEntity) {
        this.showPopup(targetEntity);
      } else {
        console.log('未在当前图层找到匹配实体');
      }
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
  }

  /**
   * 显示弹窗
   */
  showPopup(entityInfo) {
    if (!this.popup) {
      console.error('弹窗未初始化');
      return;
    }

    try {
      this.activeEntity = entityInfo;
      // 传入当前图层类型用于生成对应内容
      const content = this.generatePopupContent(entityInfo.properties, this.currentLayerType);
      this.popup.innerHTML = content;
      this.popup.style.display = 'block';
      this.updatePopupPosition();
    } catch (error) {
      console.error('显示弹窗失败:', error);
      this.hidePopup();
    }
  }

  /**
   * 根据图层类型生成对应的弹窗内容
   */
  generatePopupContent(properties, layerType) {
    if (!properties) {
      return '<div class="popup-error">无实体信息</div>';
    }
    console.log('generatePopupContent被调用', properties, layerType);

    // 基础信息（所有类型通用）
    const baseContent = `
      <div class="popup-content">
        <h3 style="margin:0 0 8px;padding-bottom:8px;border-bottom:1px solid #eee;">
          ${properties.name || '未知名称'}
        </h3>
        <p style="margin:4px 0;">经纬度：${properties.lon ? properties.lon.toFixed(6) : '未知'}, ${properties.lat ? properties.lat.toFixed(6) : '未知'}</p>
    `;

    let typeContent = '';

    // 根据图层类型生成不同内容
    switch (layerType) {
      case 'material': // 物资库图层
        typeContent = `
          ${properties.type ? `<p style="margin:4px 0;">物资类型：${properties.type}</p>` : ''}
          ${properties.quantity ? `<p style="margin:4px 0;">库存数量：${properties.quantity}</p>` : ''}
          ${properties.manufacturer ? `<p style="margin:4px 0;">生产厂商：${properties.manufacturer}</p>` : ''}
          ${properties.expiryDate ? `<p style="margin:4px 0;">过期时间：${properties.expiryDate}</p>` : ''}
          ${properties.storageLocation ? `<p style="margin:4px 0;">存放位置：${properties.storageLocation}</p>` : ''}
        `;
        break;

      case 'device': // 监测设备图层
        typeContent = `
          ${properties.deviceType ? `<p style="margin:4px 0;">设备类型：${properties.deviceType}</p>` : ''}
          ${properties.status ? `<p style="margin:4px 0;">设备状态：${properties.status}</p>` : ''}
          ${properties.installDate ? `<p style="margin:4px 0;">安装日期：${properties.installDate}</p>` : ''}
          ${properties.lastMaintenance ? `<p style="margin:4px 0;">最后维护：${properties.lastMaintenance}</p>` : ''}
          ${properties.values ? Object.entries(properties.values).map(([k, v]) =>
          `<p style="margin:4px 0;">${k}：${v}</p>`).join('') : ''}
        `;
        break;

      case 'meteorological': // 气象监测图层（预留）
        typeContent = `
          ${properties.monitorType ? `<p style="margin:4px 0;">监测类型：${properties.monitorType}</p>` : ''}
          ${properties.unit ? `<p style="margin:4px 0;">单位：${properties.unit}</p>` : ''}
          ${properties.latestValue ? `<p style="margin:4px 0;">最新值：${properties.latestValue}</p>` : ''}
          ${properties.updateTime ? `<p style="margin:4px 0;">更新时间：${properties.updateTime}</p>` : ''}
          ${properties.range ? `<p style="margin:4px 0;">正常范围：${properties.range}</p>` : ''}
        `;
        break;

      case 'population': // 人口分布图层（预留）
        typeContent = `
          ${properties.area ? `<p style="margin:4px 0;">区域：${properties.area}</p>` : ''}
          ${properties.total ? `<p style="margin:4px 0;">总人口：${properties.total}</p>` : ''}
          ${properties.density ? `<p style="margin:4px 0;">人口密度：${properties.density}</p>` : ''}
          ${properties.growthRate ? `<p style="margin:4px 0;">增长率：${properties.growthRate}</p>` : ''}
        `;
        break;

      default:
        // 默认显示所有可用字段
        typeContent = Object.entries(properties).filter(([key]) =>
          !['name', 'lon', 'lat', 'id'].includes(key)
        ).map(([key, value]) =>
          `<p style="margin:4px 0;">${key}：${value || '无'}</p>`
        ).join('');
    }

    return baseContent + typeContent + '</div>';
  }

  /**
   * 更新弹窗位置
   */
  updatePopupPosition() {
    if (!this.activeEntity || !this.popup || !this.activeEntity.entity) return;

    try {
      const cartesian = this.activeEntity.entity.position.getValue(Cesium.JulianDate.now());
      if (!cartesian) return;

      const windowPosition = this.viewer.scene.cartesianToCanvasCoordinates(cartesian);
      if (!windowPosition) return;

      const canvasRect = this.viewer.canvas.getBoundingClientRect();
      const left = windowPosition.x + canvasRect.left;
      const top = windowPosition.y + canvasRect.top;

      const popupWidth = this.popup.offsetWidth || 320;
      const popupHeight = this.popup.offsetHeight || 200;
      const viewportWidth = window.innerWidth;
      const viewportHeight = window.innerHeight;

      let finalLeft = left + 10;
      if (finalLeft + popupWidth > viewportWidth) {
        finalLeft = left - popupWidth - 10;
      }

      let finalTop = top + 10;
      if (finalTop + popupHeight > viewportHeight) {
        finalTop = top - popupHeight - 10;
      }

      this.popup.style.left = `${finalLeft}px`;
      this.popup.style.top = `${finalTop}px`;
    } catch (error) {
      console.error('更新弹窗位置失败:', error);
    }
  }

  /**
   * 隐藏弹窗
   */
  hidePopup() {
    console.log('hidePopup被调用');
    if (this.popup) {
      this.popup.style.display = 'none';
      this.popup.innerHTML = '';
    }
    this.activeEntity = null;
  }

  /**
   * 显示指定类型的图层
   */
  showLayer(type, data) {
    if (!type || !data || !Array.isArray(data)) {
      console.error('显示图层失败：参数无效');
      return;
    }
    console.log('showLayer被调用', type, data);
    // 清除当前图层
    this.clearCurrentLayer();
    this.currentLayerType = type;
    console.log(`显示图层[${type}]，数据量:`, data.length);

    const entities = [];
    data.forEach((item) => {
      const uniqueId = `layer_${type}_${item.id || Date.now()}_${Math.random().toString(36).substr(2, 8)}`;
      const entity = this.createBillboardEntity(item, uniqueId);
      if (entity) {
        entities.push({
          entity: entity,
          properties: item,
          uniqueId: uniqueId
        });
      }
    });

    this.entitiesMap.set(type, entities);
    console.log(`图层[${type}]已创建实体数量:`, entities.length);
  }

  /**
   * 创建Billboard实体
   */
  createBillboardEntity(data, uniqueId) {
    if (!data.lon || !data.lat) {
      console.warn('跳过无效实体：缺少经纬度', data);
      return null;
    }

    try {
      const position = Cesium.Cartesian3.fromDegrees(
        Number(data.lon),
        Number(data.lat),
        data.height || 0
      );

      const imageUrl = this.getImageByType(data.type);

      const entity = this.viewer.entities.add({
        id: uniqueId,
        position: position,
        billboard: {
          image: imageUrl,
          scale: 0.03,
          horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
          verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
          disableDepthTestDistance: Number.MAX_VALUE
        },
        properties: new Cesium.PropertyBag({
          uniqueId: uniqueId,
          id: data.id,
          type: data.type,
          name: data.name
        })
      });

      entity.uniqueId = uniqueId;
      return entity;
    } catch (error) {
      console.error('创建实体失败:', error, data);
      return null;
    }
  }

  /**
   * 根据实体类型获取图标路径
   */
  getImageByType(type) {
    const imageMap = {
      '医疗物资': '/src/assets/icons/2.png',
      '食品储备': '/src/assets/icons/2.png',
      '救援设备': '/src/assets/icons/2.png',
      '通讯设备': '/src/assets/icons/2.png',
      '防护装备': '/src/assets/icons/2.png',
      '气象监测': '/src/assets/icons/2.png',
      '水质监测': '/src/assets/icons/2.png',
      '空气质量': '/src/assets/icons/2.png',
      '温湿度传感器': '/src/assets/icons/2.png',
      '位移监测': '/src/assets/icons/2.png'
    };
    return imageMap[type] || '/src/assets/icons/2.png';
  }

  /**
   * 清除当前图层
   */
  clearCurrentLayer() {
    if (this.currentLayerType) {
      const entities = this.entitiesMap.get(this.currentLayerType) || [];
      entities.forEach(({ entity }) => {
        this.viewer.entities.remove(entity);
      });
      this.entitiesMap.delete(this.currentLayerType);
      console.log(`已清除图层[${this.currentLayerType}]`);
      this.currentLayerType = null;
    }
    this.hidePopup();
  }

  /**
   * 销毁图层管理器
   */
  destroy() {
    this.entitiesMap.forEach((entities) => {
      entities.forEach(({ entity }) => {
        this.viewer.entities.remove(entity);
      });
    });
    this.entitiesMap.clear();

    if (this.clickHandler) {
      this.clickHandler.destroy();
      this.clickHandler = null;
    }
    this.viewer.scene.postRender.removeEventListener(this.updatePopupPosition);
    this.hidePopup();
    if (this.popup && this.popup.parentElement) {
      this.popup.parentElement.removeChild(this.popup);
    }
    this.popup = null;
    this.viewer = null;
  }
}

export default BillboardLayerManager;